package cn.tjd.smart_health.common.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

public class QiNiuUtils {

    public static final String SK="HrdgMBg6zeOHFc0BYAJ76b3q3EaUImJnDgbCYKqV";
    public static final String AK="5hUvfhtvy9LUYBzlKOV8r52K6Y_rCq8e-uD_UINi";
    public static final String BUCKET="tjd-sh";

    public static void upload2Qiniu(String filePath, String fileName){
        Configuration conf = new Configuration(Region.region2());
        UploadManager uploadManager = new UploadManager(conf);
        Auth auth = Auth.create(AK, SK);
        String token = auth.uploadToken(BUCKET);

        try{
            Response response = uploadManager.put(filePath, fileName, token);
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(),DefaultPutRet.class);
        } catch (QiniuException e) {
            Response response = e.response;
            try{
                System.err.println(response.bodyString());
            } catch (QiniuException ex) {

            }
        }
    }

    public static void  upload2Qiniu(byte[] bytes,String fileName){
        Configuration conf = new Configuration(Region.region2());
        UploadManager uploadManager = new UploadManager(conf);
        Auth auth = Auth.create(AK, SK);
        String token = auth.uploadToken(BUCKET);

        try{
            Response response = uploadManager.put(bytes, fileName, token);
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(),DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException e) {
            Response response = e.response;
            try{
                System.err.println(response.bodyString());
            } catch (QiniuException ex) {

            }
        }
    }


    public static void deleteFileFromQiniu(String fileName){
        Configuration cfg = new Configuration(Region.region2());
        Auth auth = Auth.create(AK, SK);
        BucketManager bucketManager = new BucketManager(auth, cfg);

        try {
            bucketManager.delete(BUCKET, fileName);
        } catch (QiniuException e) {
            Response response = e.response;
            try {
                System.err.println(response.bodyString());
            } catch (QiniuException ex) {
            }
        }
    }

}
